<template>
  <div class="blog-list-container" ref="container" v-loading="isLoading">
    <ul>
      <li v-for="(item, i) in data.rows" :key="i">
        <div class="thumb" v-if="item.thumb">
          <RouterLink
            :to="{
              name: 'BlogDetail',
              params: {
                id: item.id
              }
            }"
          >
            <img v-lazy="item.thumb" :alt="item.title" :title="item.title" />
          </RouterLink>
        </div>
        <div class="main">
          <RouterLink
            :to="{
              name: 'BlogDetail',
              params: {
                id: item.id
              }
            }"
          >
            <h2>{{ item.title }}</h2>
          </RouterLink>
          <div class="aside">
            <span>日期：{{ formatDate(item.createDate) }}</span>
            <span>浏览：{{ item.scanNumber }}</span>
            <span>评论：{{ item.commentNumber }}</span>
            <RouterLink
              :to="{
                name: item.category.id == -1 ? 'Blog' : 'CategoryBlog',
                [item.category.id == -1 ? '' : 'params']: {
                  categoryId: item.category.id
                }
              }"
            >
              {{ item.category.name }}
            </RouterLink>
          </div>
          <div class="desc">
            {{ item.description }}
          </div>
        </div>
      </li>
      <Empty v-if="data.rows?.length === 0 && !isLoading" />
    </ul>
    <!-- 分页放到这里 -->
    <Pager
      v-if="data.total"
      :current="routeInfo.page"
      :total="data.total"
      :limit="routeInfo.limit"
      :visibleNumber="10"
      @pageChange="handlePageChange"
    />
  </div>
</template>

<script setup lang="ts">
import { getBlogs } from '@/api/blog'
import { formatDate } from '@/utils'
import mainScroll from '@/composition/useMainScroll'
import { useRouter } from 'vue-router'
import { getCurrentInstance, computed, watchEffect, ref, onMounted, type ComponentPublicInstance } from 'vue'
import type { getBlogListType } from '@/types/blog'
const router = useRouter()
const proxy: ComponentPublicInstance<any> = getCurrentInstance()?.proxy
let routeInfo = computed(() => {
  const categoryId = router.currentRoute.value.params.categoryId || -1
  const page = Number(router.currentRoute.value.query.page) || 1
  const limit = Number(router.currentRoute.value.query.limit) || 10
  return {
    categoryId,
    page,
    limit
  }
})
//获取博客数据

// type getBlogListType = Awaited<ReturnType<typeof getBlogs>>
const isLoading = ref(true)
const data = ref<getBlogListType>({} as getBlogListType)
onMounted(async () => {
  try {
    // 请求博客列表数据
    data.value = await getBlogs(routeInfo.value.page, routeInfo.value.limit, routeInfo.value.categoryId + '')
  } catch (error) {
    //发生异常，结束加载圈
    console.warn(error, '请求响应异常')
    isLoading.value = false
  }
})

//监控屏幕时否滚动到底部
mainScroll(proxy, 'container')

function handlePageChange(newPage: number) {
  const query = {
    page: newPage,
    limit: routeInfo.value.limit
  }
  // 跳转到 当前的分类id  当前的页容量  newPage的页码
  if (routeInfo.value.categoryId === -1) {
    // 当前没有分类
    router.push({
      name: 'Blog',
      query
    })
  } else {
    router.push({
      name: 'CategoryBlog',
      query,
      params: {
        categoryId: routeInfo.value.categoryId
      }
    })
  }
}
//路由遍布啊重新获取数据
watchEffect(async () => {
  router.currentRoute.value //监控路由变化
  isLoading.value = true
  console.log(routeInfo.value, '路由变化')

  // 滚动高度为0$route
  if (proxy.$refs.container) proxy.$refs.container.scrollTop = 0
  data.value = await getBlogs(routeInfo.value.page, routeInfo.value.limit, routeInfo.value.categoryId + '')
  isLoading.value = false
})
</script>

<style scoped lang="scss">
@import '@/styles/var.scss';

.blog-list-container {
  line-height: 1.7;
  position: relative;
  padding: 20px;
  padding-top: 35px;
  overflow-y: scroll;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  scroll-behavior: smooth;

  ul {
    list-style: none;
    margin: 0;
    padding: 0;
  }
}

li {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid $gray;
  @media screen and (max-width: 992px) {
    flex-direction: column;
  }
  .thumb {
    flex: 0 0 auto;
    margin-right: 15px;

    img {
      display: block;
      max-width: 200px;
      max-height: 100px;
      border-radius: 5px;
    }
  }

  .main {
    flex: 1 1 auto;

    h2 {
      margin: 0;
    }
  }

  .aside {
    font-size: 12px;
    color: $gray;

    span {
      margin-right: 15px;
    }
  }

  .desc {
    margin: 15px 0;
    font-size: 14px;
  }
}
</style>
